<?php

defined('SYSPATH') or die('No direct script access.');

class Controller_Zabbix extends Controller {

	private static $apiurl = 'http://zabbix.lidocs.ru/api_jsonrpc.php';
	private static $basic_auth = 'emFiYml4OlpBJDBxd2VS';
	private $auth = NULL;

	public function before() {
		parent::before();
		$this->auth = $this->auth();
	}

	public function after() {
		//$this->response->body($this->_body . (Kohana::$profiling ? View::factory('profiler/stats') : ''));
		parent::after();
	}

	private function auth() {
		$cache = Cache::instance('file');

		if ($auth = $cache->get('auth', FALSE)) {
			$cache->set('auth', $auth, 80);
		}
		else {
			$q = '{
			"jsonrpc": "2.0",
			"method": "user.login",
			"params": {
				"user": "zapix",
				"password": ">LKJHKGC78%jk,m5"
			},
			"id": 3
		}';


			$arr = $this->query($q);
			$auth = $arr['result'];
			$cache->set('auth', $auth, 80);
		}
		return $auth;
	}

	private function query($q) {
		$request = Request::factory(self::$apiurl, array('follow' => TRUE))
				->headers('Authorization', 'Basic ' . self::$basic_auth)
				->headers('Content-Type', 'application/json')
				->method(Request::POST)
				->body($q);

		$json = $request->execute();
		return json_decode($json, TRUE);
	}

	public function action_history() {


		$q = '{
   "jsonrpc": "2.0",
    "method": "history.get",
    "params": {
        "output": "extend",
        "history": 0,
        "itemids": "23275",
        "sortfield": "clock",
        "sortorder": "DESC",
        "limit": 1000
    },
   "id": 3,
   "auth": "' . $this->auth . '"
}';
		echo $this->query($q);
	}

	public function action_httptest() {
		$q = '{
			"jsonrpc": "2.0",
			"method": "httptest.create",
			"params": {
				"name": "Homepage check",
				"hostid": "10084",
				"steps": [
					{
						"name": "aircore",
						"url": "http://aircore.ru",
						"status_codes": 200,
						"no": 1
					},
					{
						"name": "aircore / map",
						"url": "http://aircore.ru/map/",
						"status_codes": 200,
						"no": 2
					}
				]
			},
		   "id": 3,
		   "auth": "' . $this->auth . '"
		}';
		$arr = $this->query($q);
		if ($id = Arr::path($arr,'result.httptestids.0',FALSE)){
			$data['httptestids'] = $id;
		}
		else {
			$data['error']= Arr::path($arr,'error.message','Unknown error');
			$data['message']= Arr::path($arr,'error.data','');
		}
		echo json_encode($data);
	}

}

// End Welcome
